package fun.lifepoem.store.controller;

import fun.lifepoem.core.domain.RestResponse;
import fun.lifepoem.core.utils.DateUtils;
import fun.lifepoem.store.domain.LpShareRecord;
import fun.lifepoem.store.domain.bo.FileShareInfo;
import fun.lifepoem.store.domain.vo.FileShareVO;
import fun.lifepoem.store.service.ShareService;
import fun.lifepoem.store.service.StoreService;
import fun.lifepoem.store.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yiwyn
 * @create 2023/2/22 21:28
 */
@Slf4j
@RestController
@RequestMapping("/store")
public class StoreController {


    @Resource
    private StoreService storeService;

    @Resource
    private ShareService shareService;


    @GetMapping("/share")
    public RestResponse<FileShareVO> share(FileShareInfo shareInfo) {
        FileShareVO fileShareVO;
        try {
            fileShareVO = storeService.shareFile(shareInfo);
            if (ObjectUtils.isEmpty(fileShareVO)) {
                return RestResponse.fail("文件找不到了");
            }
        } catch (Exception e) {
            return RestResponse.fail(e.getMessage());
        }
        return RestResponse.success(fileShareVO);
    }


    @PostMapping("/fast-share")
    public RestResponse<FileShareVO> fastShare(MultipartFile file) throws IOException {
        FileShareVO result = storeService.fastShare(file);
        return RestResponse.success(result);
    }


    @GetMapping("/read-file")
    public void readFile(String shortKey, String shareKey, HttpServletResponse response) throws IOException {

        log.info("读取文件入参 shortKey:{},shareKey:{}", shortKey, shareKey);

        LpShareRecord shareRecord = storeService.getShareRecord(shortKey, shareKey);
        RestResponse<String> result = RestResponse.fail("出现错误了");

        if (ObjectUtils.isEmpty(shareRecord)) {
            result.setMessge("该分享不存在");
            WebUtils.renderString(response, result);
        } else {
            Boolean expried = DateUtils.expried(shareRecord.getExpiryDt());
            if (expried) {
                result.setMessge("分享的文件过期了");
                shareService.expiryFile(shareRecord);
                WebUtils.renderString(response, result);
                return;
            }
            response.sendRedirect(shareRecord.getShareLink());
        }

    }
}
